const http = require("http");
const url = require("url");
const fs = require("fs");
const mysql = require("mysql");
let db = mysql.createPool({
	host:"localhost",
	user:'root',
	password:"lx1993225",
	database:"chat"
});
const server = http.createServer((req,res)=>{
	var {pathname,query} = url.parse(req.url,true);
	let {user,pass} = query;
	if(pathname=='/reg'){
		//检测数据
		if(!/^\w{6,32}$/.test(user)){
			res.write(JSON.stringify({code:1,msg:'用户名不符合规范'}))
			res.end()
		}else if(!/^.{6,32}$/.test(pass)){
			res.write(JSON.stringify({code:2,msg:'用户密码不符合规范'}));
			res.end()
		}else{
			db.query(`SELECT username FROM user_table WHERE username='${user}'`,(err,data)=>{
				if(err){
					res.write(JSON.stringify({code:1,msg:'数据有问题'}));
					res.end();
				}else if(data.length>0){
					res.write(JSON.stringify({code:1,msg:'用户名已注册'}));
					res.end();
				}else{
					db.query(`INSERT INTO user_table (username,password,online) VALUES('${user}','${pass}',0)`,(err,data)=>{
						if(err){
							res.write(JSON.stringify({code:1,msg:'注册失败'}));
							res.end()
						}else{
							res.write(JSON.stringify({code:0,msg:'注册成功'}));
							res.end()
						}
					})

				}
			});
		};
	}else if(pathname=='/log'){
		//检测数据
		if(!/^\w{6,32}$/.test(user)){
			res.write(JSON.stringify({code:1,msg:'用户名不符合规范'}))
			res.end()
		}else if(!/^.{6,32}$/.test(pass)){
			res.write(JSON.stringify({code:2,msg:'用户密码不符合规范'}));
			res.end();
		}else{
			db.query(`SELECT ID,password FROM user_table WHERE username='${user}'`,(err,data)=>{
				if(err){
					res.write(JSON.stringify({code:1,msg:'数据有问题'}));
					res.end();
				}else if(data.length==0){
					res.write(JSON.stringify({code:1,msg:'用户不存在'}));
					res.end();
				}else if(data[0].password!=pass){
					res.write(JSON.stringify({code:1,msg:'用户不或密码错误'}));
					res.end();
				}else{
					db.query(`UPDATE user_table SET online=1 WHERE ID='${data[0].ID}'`,(err,data)=>{
						if(err){
							res.write(JSON.stringify({code:1,msg:'数据库错误'}));
							res.end();
						}else{
							res.write(JSON.stringify({code:0,msg:'登录成功'}));
							res.end();
						}
					})
				}
			})
		}
	}else{
		fs.readFile('2.txt',(err,data)=>{
			if(err){
				fs.readFile('404.html',(err,data)=>{
					if(err){
						res.writeHeader("404");
						res.write("NOT FOUND")
					}else{
						res.write(data)
					}
					res.end()
				})
			}else{
				console.log(data.toString())
				res.write(data.toString());
				res.end()
			}

		})
	};
})
server.listen(8080)